import type { RouteRecordRaw } from 'vue-router'
import { authService } from '@/api/auth'
import type { Permission } from '@/types'

// 缓存键
const CACHE_KEYS = {
  USER_PERMISSIONS: 'user_permissions_cache',
  DYNAMIC_ROUTES: 'dynamic_routes_cache',
  ROUTES_INITIALIZED: 'routes_initialized'
}

// 缓存工具函数
function setCache<T>(key: string, data: T, expiry: number = 30 * 60 * 1000): void {
  const cacheItem = {
    data,
    timestamp: Date.now(),
    expiry
  }
  localStorage.setItem(key, JSON.stringify(cacheItem))
}

function getCache<T>(key: string): T | null {
  try {
    const cached = localStorage.getItem(key)
    if (!cached) return null

    const cacheItem = JSON.parse(cached)
    const now = Date.now()
    
    // 检查是否过期
    if (now - cacheItem.timestamp > cacheItem.expiry) {
      localStorage.removeItem(key)
      return null
    }
    
    return cacheItem.data
  } catch (error) {
    localStorage.removeItem(key)
    return null
  }
}

function clearCache(key: string): void {
  localStorage.removeItem(key)
}

function clearAllRouteCache(): void {
  Object.values(CACHE_KEYS).forEach(key => {
    localStorage.removeItem(key)
  })
}

// 使用import.meta.glob预先收集所有views组件
const viewModules = import.meta.glob('@/views/**/index.vue')


// 根据路径获取组件 - 使用预收集的模块映射
function getComponentByPath(routePath: string) {
  // 路径标准化处理
  const normalizedPath = routePath
    .replace(/^\/+/, '') // 移除开头的斜杠
    .replace(/\/+$/, '') // 移除结尾的斜杠
    .replace(/\/+/g, '/') // 多个斜杠合并为一个
  
  // 处理特殊情况
  if (!normalizedPath || normalizedPath === '') {
    return () => import('@/views/dashboard/index.vue')
  }
  
  // 生成可能的组件路径列表（同时支持@和/src格式）
  const possiblePaths = [
    `@/views/${normalizedPath}/index.vue`, // @格式
    `/src/views/${normalizedPath}/index.vue`, // /src格式
    `@/views/${normalizedPath.replace(/\//g, '-')}/index.vue`, // @格式短横线
    `/src/views/${normalizedPath.replace(/\//g, '-')}/index.vue`, // /src格式短横线
  ]
  
  // 在预收集的模块中查找匹配的路径
  for (const path of possiblePaths) {
    if (viewModules[path]) {
      return viewModules[path] as () => Promise<any>
    }
  }
  
  // 如果没有找到精确匹配，尝试模糊匹配
  const fuzzyMatches = Object.keys(viewModules).filter(modulePath => {
    // 统一处理路径格式，移除前缀和后缀进行比较
    const cleanModulePath = modulePath
      .replace(/^@\/views\//, '') // 移除@/views/前缀
      .replace(/^\/src\/views\//, '') // 移除/src/views/前缀  
      .replace(/\/index\.vue$/, '') // 移除/index.vue后缀
    
    return cleanModulePath === normalizedPath || 
           cleanModulePath.replace(/\//g, '-') === normalizedPath ||
           cleanModulePath.replace(/-/g, '/') === normalizedPath
  })
  
  if (fuzzyMatches.length > 0) {
    const matchedPath = fuzzyMatches[0]
    return viewModules[matchedPath] as () => Promise<any>
  }
  
  return () => import('@/views/dashboard/index.vue')
}

// 生成动态路由
function generateDynamicRoutes(permissions: Permission[]): RouteRecordRaw[] {
  // 过滤出有效的菜单类型权限
  const menuPermissions = permissions.filter(p => {
    const isVisible = p.show === undefined || p.show === 1
    const hasValidUrl = p.type === 1 && p.menuUrl && p.menuUrl !== '#' && p.menuUrl !== null
    return isVisible && hasValidUrl
  })
  
  const routes: RouteRecordRaw[] = []
  
  // 为每个菜单权限创建独立的顶级路由，使用Layout包装
  menuPermissions.forEach(permission => {
    const routePath = permission.menuUrl!
    
    const route: RouteRecordRaw = {
      path: routePath,
      name: permission.permissionKey || `route_${permission.id}`,
      component: () => import('@/layout/index.vue'),
      children: [
        {
          path: '',
          name: `${permission.permissionKey || `route_${permission.id}`}_Page`,
          component: getComponentByPath(routePath),
          meta: {
            title: permission.permissionName,
            icon: permission.icon,
            permission: permission.permissionKey,
            breadcrumb: true
          }
        }
      ],
      meta: {
        title: permission.permissionName,
        icon: permission.icon,
        permission: permission.permissionKey
      }
    }
    
    routes.push(route)
  })
  
  return routes
}

// 添加动态路由到路由表
function addDynamicRoutesToRouter(router: any, routes: RouteRecordRaw[]): void {
  routes.forEach(route => {
    try {
      router.addRoute(route)
    } catch (error) {
      console.error('添加路由失败:', route.path, error)
    }
  })
}

// 检查用户是否有访问某个路径的权限
export function hasPermissionForPath(path: string): boolean {
  const cachedPermissions = getCache<Permission[]>(CACHE_KEYS.USER_PERMISSIONS)
  if (!cachedPermissions) {
    return false
  }
  
  // 检查是否有对应路径的权限
  return cachedPermissions.some(p => 
    p.type === 1 && p.menuUrl === path && (p.show === undefined || p.show === 1)
  )
}

// 获取缓存的权限数据
export function getCachedPermissions(): Permission[] | null {
  return getCache<Permission[]>(CACHE_KEYS.USER_PERMISSIONS)
}

// 清理所有路由相关缓存
export function clearAllRouteCaches(): void {
  clearAllRouteCache()
}

// 主要的动态路由初始化函数 - 在应用启动时调用
export async function initializeDynamicRoutes(router: any): Promise<{ success: boolean; error?: string }> {
  try {
    
    // 检查是否已有缓存的权限数据
    let permissions = getCache<Permission[]>(CACHE_KEYS.USER_PERMISSIONS)
    
    if (!permissions || permissions.length === 0) {
      
      // 尝试从API获取权限数据
      try {
        permissions = await authService.getCurrentUserPermissions()
        
        if (!permissions || permissions.length === 0) {
          return { success: false, error: '权限数据为空' }
        }
        
        // 缓存权限数据
        setCache(CACHE_KEYS.USER_PERMISSIONS, permissions, 30 * 60 * 1000)
      } catch (apiError) {
        return { success: false, error: '获取权限失败' }
      }
    } 
    
    // 生成动态路由
    const dynamicRoutes = generateDynamicRoutes(permissions)
    
    if (dynamicRoutes.length === 0) {
      return { success: true }
    }
    
    // 添加到路由表
    addDynamicRoutesToRouter(router, dynamicRoutes)
    
    // 缓存路由数据和初始化状态
    setCache(CACHE_KEYS.DYNAMIC_ROUTES, dynamicRoutes, 30 * 60 * 1000)
    setCache(CACHE_KEYS.ROUTES_INITIALIZED, true, 30 * 60 * 1000)
    
    return { success: true }
    
  } catch (error) {
    return { success: false, error: error instanceof Error ? error.message : '未知错误' }
  }
} 